import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:seedfour/app/checkupdate/update_dialog.dart';

class UpdateInfo {
  final String version;
  final bool isForceUpdate;
  final String description;
  final String apkUrl;
  final String iosAppStoreUrl;
  final String releaseNotes;
  final int fileSize;

  UpdateInfo({
    required this.version,
    required this.isForceUpdate,
    required this.description,
    required this.apkUrl,
    required this.iosAppStoreUrl,
    required this.releaseNotes,
    required this.fileSize,
  });

  factory UpdateInfo.fromJson(Map<String, dynamic> json) {
    return UpdateInfo(
      version: json['version'],
      isForceUpdate: json['force_update'] ?? false,
      description: json['description'] ?? '新版本可用',
      apkUrl: json['apk_url'] ?? '',
      iosAppStoreUrl: json['ios_app_store_url'] ?? '',
      releaseNotes: json['release_notes'] ?? '',
      fileSize: json['file_size'] ?? 0,
    );
  }
}

class UpdateService {
  static var isShown = false;
  static Future<PackageInfo> get localVersion async {
    return await PackageInfo.fromPlatform();
  }
  static Future<void> doCheckForUpdates() async {
    if(isShown){
      return;
    }
    try {
      EasyLoading.show(status: '检查更新中...');
      final updateInfo = await checkForUpdate();
      EasyLoading.dismiss();

      if (updateInfo != null) {
        Get.dialog(
          UpdateDialog(updateInfo: updateInfo),
          barrierDismissible: !updateInfo.isForceUpdate,
        );
      }
      isShown = true;
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('更新检查失败: $e', duration: const Duration(seconds: 2));
    }
  }
  static Future<UpdateInfo?> checkForUpdate() async {
    try {
      // 替换为您的实际API地址
      const url = 'https://api.seedfour.com/mobile/api/v1/app/check-ver';
      final response = await http.get(Uri.parse(url));

      if (response.statusCode == 200) {
        Map<String, dynamic> jsonResponse = json.decode(response.body);

        if(jsonResponse['data'] != null){
          jsonResponse = jsonResponse['data'];
        }
        final remoteVersion = UpdateInfo.fromJson(jsonResponse);
        final localInfo = await localVersion;

        if (_isNewerVersion(localInfo.version, remoteVersion.version)) {
          return remoteVersion;
        }
      }
      return null;
    } catch (e) {
      throw Exception('更新检查失败: $e');
    }
  }

  static bool _isNewerVersion(String local, String remote) {
    final localParts = local.split('.').map(int.tryParse).toList();
    final remoteParts = remote.split('.').map(int.tryParse).toList();

    for (var i = 0; i < remoteParts.length; i++) {
      final remotePart = remoteParts[i] ?? 0;
      final localPart = i < localParts.length ? (localParts[i] ?? 0) : 0;

      if (remotePart > localPart) return true;
      if (remotePart < localPart) return false;
    }
    return false;
  }
}